package com.example.mqttcar.mqtt;

import org.eclipse.paho.client.mqttv3.*;

public class EmqxJavaDemo {
    public static void main(String[] args) {
        String broker = "tcp://127.0.0.1:1883"; // EMQX 服务器地址
        String clientId = "JavaClient";
        String topic = "topic/test";

        try {
            // 1. 创建 MQTT 客户端
            MqttClient client = new MqttClient(broker, clientId);

            // 2. 设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("收到消息: " + new String(message.getPayload()));
                }

                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println(cause.getMessage());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {}
            });

            // 3. 连接 EMQX
            client.connect();
            System.out.println("连接成功！");

            // 4. 订阅主题
            client.subscribe(topic);

            // 5. 发布消息
            String content = "你会";
            client.publish(topic, new MqttMessage(content.getBytes()));

            // 保持连接（测试用）
            Thread.sleep(5000);
            client.disconnect();

        } catch (MqttException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
